﻿using Learun.Application.Base.AuthorizeModule;
using Learun.Util;
using Learun.Util.Operat;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace Learun.Application.Web
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：-框架开发组
    /// 日 期：2017.03.08
    /// 描 述：登录认证（会话验证组件）
    /// </summary>
    public class HandlerAppLoginAttribute : AuthorizeAttribute
    {
        private DataAuthorizeIBLL dataAuthorizeIBLL = new DataAuthorizeBLL();
        private FilterMode _customMode;
        private bool IsApp = false;
        /// <summary>默认构造</summary>
        /// <param name="Mode">认证模式</param>
        public HandlerAppLoginAttribute(FilterMode Mode, bool isApp = false)
        {
            _customMode = Mode;
            IsApp = isApp;
        }
        /// <summary>
        /// 响应前执行登录验证,查看当前用户是否有效 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(HttpActionContext filterContext)
        {
            // 登录拦截是否忽略
            if (_customMode == FilterMode.Ignore)
            {
                return;
            }
            string userId = WebHelper.GetSession("AppUserId");
            if (string.IsNullOrEmpty(userId))
            {
                HandleUnauthorizedRequest(filterContext);
                return;
            }
            // 验证登录状态
            int res = OperatorHelper.Instance.IsOnLine("", "").stateCode;
            if (res != 1)// 登录过期或者未登录
            {
                HandleUnauthorizedRequest(filterContext);
                return;
            }
        }
        // 这个方法 会在验证失败时调用,可以设定返回状态值和返回信息.
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);
            var response = actionContext.Response = actionContext.Response ?? new System.Net.Http.HttpResponseMessage();
            // 这句话可以改变请求状态值 就是 200 403 之类的那个状态值
            response.StatusCode = System.Net.HttpStatusCode.OK;
            // 将这个出错信息加入到返回对象中.
            var returnContext = new ResParameter { code = ResponseCode.nologin, info = "登录过期或者未登录" }.ToJson();
            response.Content = new StringContent(returnContext);
        }

    }
}